<?php

declare(strict_types=1);

namespace app\common\command\storage;

use app\admin\model\StorageChunkCache;
use app\common\tools\StorageTools;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Log;

class ChunkCacheMove extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('storage:chunk:cache:move')
            ->setDescription('the storage:chunk:cache:move command');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('storage:chunk:cache:move');


        while (true) {
            $model_chunk_cache = StorageChunkCache::where('host_key', Config::get('storage.host_key'))->where('status', 0)->find();

            if (empty($model_chunk_cache)) {
                sleep(1);
                continue;
            }

            $file_path = StorageTools::buildChunkCachePath($model_chunk_cache->chunk_md5);

            if (!file_exists($file_path)) {
                Log::error('迁移chunk缓存发生意外，缓存不存在');
                $model_chunk_cache->msg = '迁移chunk缓存发生意外，缓存不存在';
                $model_chunk_cache->status = 1;
                $model_chunk_cache->save();
                continue;
            }

            try {
                $file_contents = file_get_contents($file_path);
                StorageTools::write($file_contents, $model_chunk_cache->chunk_md5, true);

                unlink($file_path);
                $model_chunk_cache->msg = '迁移成功';
                $model_chunk_cache->status = 2;
                $model_chunk_cache->save();
            } catch (\Throwable $th) {
                //throw $th;
                Log::error('迁移chunk缓存发生意外,迁移错误');
                Log::error($th);
                $model_chunk_cache->msg = '迁移chunk缓存发生意外，迁移错误';
                $model_chunk_cache->status = 1;
                $model_chunk_cache->save();
                continue;
            }
        }
    }
}
